{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from PyPDF2 import PdfMerger\n",
    "import os\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def list_files(directory):\n",
    "    # 检查目录是否存在\n",
    "    if not os.path.exists(directory):\n",
    "        print(\"目录不存在\")\n",
    "        return\n",
    "\n",
    "    # 获取目录中的文件和文件夹列表\n",
    "    files_and_dirs = os.listdir(directory)\n",
    "\n",
    "    # 过滤出文件列表\n",
    "    files = [file for file in files_and_dirs if os.path.isfile(os.path.join(directory, file))]\n",
    "\n",
    "    return files\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件列表: ['2230026125-Runjie MIAO-2024-09-02-13-39.pdf', '2430026079-Yutao JIANG-2024-09-02-13-39.pdf', '2430026080-Zekang JIANG-2024-09-02-13-38.pdf', '2430026080-Zekang JIANG-2024-09-02-13-40.pdf', '2430026122-Xiaotong LIN-2024-09-02-13-39.pdf']\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# 指定要打开的文件夹路径\n",
    "folder_path = 'merge_pdf'\n",
    "\n",
    "# 获取并打印文件列表\n",
    "file_list = list_files(folder_path)\n",
    "print(\"文件列表:\", file_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建一个PdfMerger对象\n",
    "merger = PdfMerger()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "for f in file_list:\n",
    "    pdf = open(f'{folder_path}/{f}','rb')\n",
    "    merger.append(pdf)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将合并的PDF文件保存为新的PDF文件\n",
    "merged_pdf = open(f'{folder_path}/merged.pdf', 'wb')\n",
    "merger.write(merged_pdf)\n",
    "\n",
    "# 关闭文件\n",
    "pdf.close()\n",
    "merged_pdf.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ispace_venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
